<?php

namespace app\videos\server;

use app\common\server\Service;
use app\videos\model\Replay as ReplayModel;

class Replay extends Service
{

    public function initialize()
    {
        parent::initialize();
        if (!isset($this->serviceKey) || empty($this->serviceKey) || cache('serviceKey') != $this->serviceKey) {
            exit(json_encode(['msg' => '非法操作！', 'code' => 712]));
        }
        $this->ReplayModel = new ReplayModel();
    }

    public function getVodReplay($data, $user)
    {

        if (!isset($data['vid']) || empty($data['vid'])) {
            $this->error = '获取id失败';
            return false;
        }

        $map = [];
        $map[] = ['vod_id', 'eq', $data['vid']];
        $map[] = ['status', 'eq', 1];

        $page = isset($data['page']) && !empty($data['page']) ? $data['page'] : 1;
        $limit = isset($data['limit']) && !empty($data['limit']) ? $data['limit'] : 10;

        $order = 'create_time desc';
        if ($user && $user['id'] > 0) {
            $order = "uid = {$user['id']} desc, create_time desc";
        }
        $map['cache'] = false;
        return $this->ReplayModel->getList($map, $page, $limit, $order);
    }

    public function sendReplay($data, $user)
    {
        if (!isset($user['id']) || empty($user)) {
            $this->error = '请先登录';
            $this->code = 1200;
            return false;
        }

        if (mb_strlen($data['content']) > 500) {
            $this->error = '最大长度不能超过500字';
            return false;
        }
        
        // 校验是否已评论
        $map = [];
        $map[] = ['uid', 'eq', $user['id']];
        $map[] = ['vod_id', 'eq', $data['vod_id']];
        $info = $this->ReplayModel->where($map)->find();
        if ($info) {
            $this->error = '您已提交过评论啦';
            return false;
        }
        $data = [
            'uid' => $user['id'],
            'vod_id' => $data['vod_id'],
            'vod_name' => $data['vod_name'],
            'content' => $data['content'],
            'avatar' => urldecode(trim(base64_decode($data['avatar']), '"')),
            'nickname' => $data['nickname'],
        ];
        return $this->ReplayModel->allowField(true)->save($data);
    }
}
